<?php

/**
 * Created by PhpStorm.
 * User: fang
 * Date: 2017/11/24
 * Time: 上午9:47
 */
class Audit
{
    static private $access_token;

    const API_HOST = 'https://api.weixin.qq.com';

    const MODIFY_DOMAIN = '/wxa/modify_domain';
    const CODE_COMMIT = '/wxa/commit';
    const GET_CATEGORY = '/wxa/get_category';
    const GET_PAGE = '/wxa/get_page';
    const SUBMIT_AUDIT = '/wxa/submit_audit';
    const RELEASE = '/wxa/release';
    const WXACODE = '/wxa/getwxacode';
    const GET_QRCODE = '/wxa/get_qrcode';
    const TOKENS = '/cgi-bin/token';
    const LATESTAUDIT = '/wxa/get_latest_auditstatus';



    /**
     * 构造函数
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
     * @param $appid string 小程序的appid
     */
    public function __construct($access_token)
    {
        self::$access_token = $access_token;
    }
    public function modify_domain($modify_domain){
        $params = [
            'action'=>'add',
            'requestdomain'=>["https://{$modify_domain}"],
            'wsrequestdomain'=>["wss://{$modify_domain}"],
            'uploaddomain'=>["https://{$modify_domain}"],
            'downloaddomain'=>["https://{$modify_domain}"]
        ];
        $retData = self::Requests(self::API_HOST.self::MODIFY_DOMAIN."?access_token=".self::$access_token['authorizer_access_token'],$params);
        $retData = !empty($retData)?json_decode($retData, true):false;
        return $retData;
    }
    public function code_commit($data=[]){
//        $version="v1.02";

        $domain = \app\common\model\Base::get_web_domain($data["web_id"]);
        $domain_set = \app\common\model\Base::get_domain_set('curl_api');
        //获取最新的模板
        $descript = !empty(self::$access_token["nick_name"])?self::$access_token["nick_name"]:(!empty($domain)?$domain:'test');
        $last_templet = \think\Loader::model('wechat/mini_program')->get_user_templet($data['web_id']);
        //获取客户最新的审核记录
        $version = $last_templet['user_version']??0;
        //获取mp域名
        $domain = \app\common\model\Base::domain_preg($domain,5);
        $extJson =[
            'extEnable' => true,
            'extAppid' => self::$access_token["appid"],
            'ext' => [
                "apiBase"=>"https://".$domain_set,
                "domain"=>$domain,
                "web_id"=>$data["web_id"],
                "version_id"=>$version,
                "picdomain"=>config('qiniu.DOMAIN'),
            ]
        ];
        \think\Db::name('Test')->insert(['web_id'=>192,'test'=>serialize($extJson)]);
        $params = array(
            'template_id'   => !empty($last_templet['templet_id'])?$last_templet['templet_id']:0,
            'user_version'  => $version,
            'user_desc'     => $descript,
            'ext_json'      => json_encode( $extJson, JSON_UNESCAPED_UNICODE )
        );
        $retData = self::Requests(self::API_HOST.self::CODE_COMMIT."?access_token=".self::$access_token['authorizer_access_token'],$params);
        $retData = !empty($retData)?json_decode($retData, true):false;
//        echo json_encode($retData);die;
        if ($retData['errcode'] == 0){
            //成功  将第三方提交的代码包提交审核
            $category = self::get_category();
            //获取代码包页面
            $page_url = $last_templet['path']??'';
            if(empty($last_templet['path'])){
                $page_url = self::get_page();
                \think\Loader::model('wechat/mini_program')->edit_mini_templet(['id'=>$last_templet['id'],'path'=>$page_url]);
            }
            $descript_sub = mb_substr($descript,0,10,'utf-8');
            $datas['item_list'] = [
                0 => [
                    "address" => $page_url,
                    "tag" => $descript_sub,
                    "first_class" => $category["first_class"],
                    "second_class" => $category["second_class"],
                    "first_id" => "{$category['first_id']}",
                    "second_id" => "{$category["second_id"]}",
                    "title" => $descript
                ]
            ];
            $retData = self::Requests(self::API_HOST.self::SUBMIT_AUDIT."?access_token=".self::$access_token['authorizer_access_token'],$datas);
            $retData = !empty($retData)?json_decode($retData, true):[];
            $new['retData'] = $retData;
            $new['datas'] = $datas;
            $new['cate'] = $category;
            $new['pages'] = $page_url;
            if ($retData['errcode'] == 0){
                //代码包提交审核成功
                \think\Loader::model('wechat/mini_program')->add_audit([
                    'web_id' => $data['web_id'],
                    'auditid' =>$retData['auditid'],
                    'templet_id' => !empty($last_templet['templet_id'])?$last_templet['templet_id']:0,
                    'status' => 2,
                    'reason' =>'审核中',
                    'version' =>$version
                ]);
                return $retData;
            }else{
                return $retData;
            }
        }
        return $retData;
    }
    /**
     * @return bool
     * 获取授权小程序帐号的可选类目
     */
    static public function get_category(){
        $retData = self::Requests(self::API_HOST.self::GET_CATEGORY."?access_token=".self::$access_token['authorizer_access_token'],[],'GET');
        $retData = !empty($retData)?json_decode($retData, true):false;
        if(!empty($retData) &&  $retData['errcode'] == 0){
            return !empty($retData['category_list'][0])?$retData['category_list'][0]:false;
        }else{
            return false;
        }
    }
    /**
     * @param $access_token
     * @return bool
     * 获取小程序的第三方提交代码的页面配置
     */
    public function get_page(){
        $retData = self::Requests(self::API_HOST.self::GET_PAGE."?access_token=".self::$access_token['authorizer_access_token'],[],'GET');
        $retData = !empty($retData)?json_decode($retData, true):false;
        if(!empty($retData) &&  $retData['errcode'] == 0){
            return !empty($retData['page_list'][0])?$retData['page_list'][0]:false;
        }else{
            return false;
        }
    }
    /**
     * 发布已通过审核的小程序
     */
    public function release($result=[]){
        $retData = self::Requests(self::API_HOST.self::RELEASE."?access_token=".self::$access_token['authorizer_access_token'],(object)[]);
        $retData = !empty($retData)?json_decode($retData, true):false;
        //发布成功,更新状态
        if(0 == $retData['errcode']){
            db('wechat_audit')->where(['id'=>$result['audit_id']])->update(['status'=>4,'reason'=>'发布成功']);
        }
//        echo \GuzzleHttp\json_encode($retData);die;
        return $retData['errcode'];
    }
    public function get_latest_auditstatus(){
        $retData = self::Requests(self::API_HOST.self::LATESTAUDIT."?access_token=".self::$access_token['authorizer_access_token'],[],'GET');
        $retData = !empty($retData)?json_decode($retData, true):false;
        if(!empty($retData) &&  $retData['status'] == 0){
            return true;
        }else{
            return false;
        }
    }
    /**
     * @param array $wechat_config
     * @return bool
     *  获取公众号授权信息
     */
    public function token($wechat_config=[]){
        $retData = self::Requests(self::API_HOST.self::TOKENS."?grant_type=client_credential&appid=".$wechat_config['appid']."&secret=".$wechat_config['appsecret'],[],'GET');
        $retData = !empty($retData)?json_decode($retData, true):false;
        if(!empty($retData['access_token'])){
            return $retData['access_token'];
        }else{
            return false;
        }
    }

    /**
     * 获取微信二维码
     */
    public function getwxacode($data=[]){
        $retDatas = self::Requests(self::API_HOST.self::WXACODE."?access_token=".$data['access_token'],$data['templet']);
        //将生成的小程序码存入相应文件夹下
        if(strstr($retDatas,"errcode")){
            return false;
        }
        return $retDatas;
    }
    /**
     * 获取体验小程序的体验二维码
     */
    public function get_qrcode(){
        $url = self::API_HOST.self::GET_QRCODE."?access_token=".self::$access_token['authorizer_access_token'];
        return $url;
    }
    /**
     * @desc 封装curl的调用接口，post的请求方式
     */
    static public function Requests($url, $params=[], $method='POST',$timeout = 20) {
        if(empty($url) || $timeout <= 0){
            return false;
        }
        if($method == 'GET' && !empty($params)) {
            $url = $url . '?' . http_build_query($params);
        }
        $con = curl_init((string)$url);
        curl_setopt($con, CURLOPT_HEADER, false);
        if($method == 'POST'){
            curl_setopt($con, CURLOPT_POSTFIELDS, json_encode($params,JSON_UNESCAPED_UNICODE));
            curl_setopt($con, CURLOPT_POST, true);
        }
        curl_setopt($con, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($con, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($con, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

        return curl_exec($con);
    }
}